<template>
  <div class="forget-password-container">
    <div class="forget-password-card">
      <div class="card-title">
        <h2>重置密码</h2>
        <p>通过邮箱验证码重置密码</p>
      </div>
      <el-form
        :model="forgetForm"
        :rules="forgetRules"
        ref="forgetFormRef"
        label-width="0px"
      >
        <el-form-item prop="email">
          <el-input
            v-model="forgetForm.email"
            placeholder="注册邮箱"
            prefix-icon="el-icon-message"
          ></el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-row :gutter="10">
            <el-col :span="16">
              <el-input
                v-model="forgetForm.code"
                placeholder="验证码"
                prefix-icon="el-icon-verification"
              ></el-input>
            </el-col>
            <el-col :span="8">
              <el-button
                :disabled="sendingCode || codeSent"
                @click="sendVerificationCode"
                class="get-code-button"
              >
                {{ codeSent ? `已发送(${countdown}s)` : "获取验证码" }}
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item prop="newPassword">
          <el-input
            v-model="forgetForm.newPassword"
            type="password"
            placeholder="新密码"
            prefix-icon="el-icon-lock"
          ></el-input>
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="forgetForm.confirmPassword"
            type="password"
            placeholder="确认新密码"
            prefix-icon="el-icon-lock"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            @click="handleResetPassword"
            class="reset-button"
          >
            重置密码
          </el-button>
        </el-form-item>
      </el-form>
      <div class="reset-option">
        <router-link to="/login" class="option-link">返回登录</router-link>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "ForgetPassword",
  data() {
    return {
      forgetForm: {
        email: "",
        code: "",
        newPassword: "",
        confirmPassword: "",
      },
      forgetRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" },
        ],
        code: [{ required: true, message: "请输入验证码", trigger: "change" }],
        newPassword: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          { min: 6, message: "密码长度至少为6位", trigger: "blur" },
        ],
        confirmPassword: [
          { required: true, message: "请确认新密码", trigger: "blur" },
          { validator: this.validateConfirmPassword, trigger: "blur" },
        ],
      },
      loading: false,
      sendingCode: false,
      codeSent: false,
      countdown: 60,
      timer: null,
    };
  },
  methods: {
    validateConfirmPassword(rule, value, callback) {
      if (value !== this.forgetForm.newPassword) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    },
    sendVerificationCode() {
      this.$refs.forgetFormRef.validateField("email", (errorMessage) => {
        // 修改点1：这里判断的是errorMessage是否存在，而不是valid
        if (errorMessage) {
          this.$message.error(errorMessage);
          return;
        }

        this.sendingCode = true;

        console.log("发送验证码请求:", this.forgetForm.email);

        // 模拟请求
        // setTimeout(() => {
        //   this.$message.success('验证码已发送（模拟）');
        //   this.codeSent = true;
        //   this.startCountdown();
        //   this.sendingCode = false;
        // }, 1000);

        this.$axios
          .post("/user/sendVerificationCode", {
            email: this.forgetForm.email,
          })
          .then((res) => {
            if (res.data.code === 200) {
              this.$message.success("验证码已发送，请查收邮箱");
              this.codeSent = true;
              this.startCountdown();
            } else {
              this.$message.error(res.data.message);
            }
          })
          .catch((err) => {
            console.error("发送验证码失败:", err);
            this.$message.error("发送验证码失败，请稍后重试");
          })
          .finally(() => {
            this.sendingCode = false;
          });
      });
    },
    startCountdown() {
      if (this.timer) clearInterval(this.timer);

      this.timer = setInterval(() => {
        this.countdown--;
        if (this.countdown <= 0) {
          clearInterval(this.timer);
          this.codeSent = false;
          this.countdown = 60;
        }
      }, 1000);
    },
    handleResetPassword() {
      this.$refs.forgetFormRef.validate((valid) => {
        if (valid) {
          this.loading = true;
          const { email, code, newPassword } = this.forgetForm;
          const info = { email, code, newPassword };

          // 模拟请求测试
          // setTimeout(() => {
          //   this.$message.success('密码重置成功（模拟）');
          //   this.loading = false;
          //   this.$router.push('/login');
          // }, 1000);

          this.$axios
            .post("/user/resetPassword", info)
            .then((res) => {
              if (res.data.code === 200) {
                this.$message.success("密码重置成功，请使用新密码登录");
                this.$router.push("/login");
              } else {
                this.$message.error(res.data.message);
              }
            })
            .catch((err) => {
              console.error("重置密码失败:", err);
              this.$message.error("重置密码失败，请稍后重试");
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
  },
  beforeDestroy() {
    if (this.timer) clearInterval(this.timer);
  },
};
</script>

<style scoped>
.forget-password-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 180px);
  padding: 20px;
}

.forget-password-card {
  background-color: white;
  border-radius: 20px;
  box-shadow: -10px -10px 20px rgba(255, 255, 255, 0.8),
    10px 10px 20px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 400px;
  position: relative;
  overflow: hidden;
}

.forget-password-card::before {
  content: "";
  position: absolute;
  top: -30px;
  right: -30px;
  width: 60px;
  height: 60px;
  background-color: rgba(255, 183, 107, 0.2);
  border-radius: 50%;
}

.forget-password-card::after {
  content: "";
  position: absolute;
  bottom: -30px;
  left: -30px;
  width: 60px;
  height: 60px;
  background-color: rgba(255, 183, 107, 0.2);
  border-radius: 50%;
}

.card-title {
  margin-bottom: 30px;
}

.card-title h2 {
  font-size: 28px;
  color: #303133;
  margin-bottom: 10px;
}

.card-title p {
  color: #909399;
}

.get-code-button {
  width: 100%;
  border-radius: 20px;
  height: 40px;
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
  transition: all 0.3s;
}

.get-code-button:hover:not(:disabled) {
  background-color: #e4e7ed;
  border-color: #dcdfe6;
}

.reset-button {
  width: 100%;
  border-radius: 20px;
  background-color: #ffb76b;
  border-color: #ffb76b;
  height: 40px;
  transition: all 0.3s;
}

.reset-button:hover {
  background-color: #ff9d34;
  border-color: #ff9d34;
  transform: translateY(-2px);
  box-shadow: 0 5px 10px rgba(255, 157, 52, 0.2);
}

.reset-option {
  margin-top: 20px;
  text-align: center;
}

.option-link {
  color: #909399;
  text-decoration: none;
  transition: color 0.3s;
}

.option-link:hover {
  color: #ffb76b;
}
</style>